package com.sqk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sqk.reggie.common.BaseContext;
import com.sqk.reggie.common.Result;
import com.sqk.reggie.pojo.ShoppingCart;
import com.sqk.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 购物车
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加商品
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody ShoppingCart shoppingCart){

        shoppingCart.setUserId(BaseContext.getCurrentId());

        shoppingCartService.save(shoppingCart);

        return Result.success("添加成功!");
    }

    /**
     * 购物清单
     * @return
     */
    @GetMapping("/list")
    public Result<List<ShoppingCart>> list(){
        //查询当前用户的购物车
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
        return Result.success(shoppingCartList);
    }

    /**
     * 修改购物车内容
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public Result<String> delete(@RequestBody ShoppingCart shoppingCart){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId());
        queryWrapper.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());

        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        if (shoppingCarts.size() > 1){
            ShoppingCart first = shoppingCarts.get(0);
            Long id = first.getId();
            shoppingCartService.removeById(id);
            return Result.success("修改成功!");
        }

        shoppingCartService.remove(queryWrapper);
        return Result.success("修改成功!");
    }
}
